#import "RNItem.h"
#import "RNListItem.h"
#import "RNCategory.h"
#import "RNAisle.h"
#import "NSManagedObject+SRAdditions.h"
#import "RNFavorites.h"

@implementation RNItem 

@dynamic confidence;
@dynamic title;
@dynamic listItems;
@dynamic historyItems;
@dynamic category;
@dynamic aisles;
@dynamic favorite;
@dynamic icon;

+(NSSet *)keys {
    return [NSSet setWithObjects:@"title", @"favorite", @"category", @"listItems", nil];
}

+(NSSet *)keyPathsForValuesAffectingObjectDictionary {
    return [self keys];
}

-(NSDictionary *)objectDictionary {
    return [self dictionaryWithValuesForKeys:[[RNItem keys] allObjects]];
}

-(NSDictionary *)dictionaryRepresentation {
    NSMutableDictionary *dictionaryRepresentation = [NSMutableDictionary dictionary];
    [dictionaryRepresentation setValue:[self title] forKey:@"title"];
    [dictionaryRepresentation setValue:[self favorite] forKey:@"favorite"];
    [dictionaryRepresentation setValue:[[self category] URIRepresentation] forKey:@"category"];
    NSMutableSet *aisleURIs = [NSMutableSet set];
    for (NSManagedObject *aisle in [self aisles]) 
        [aisleURIs addObject:[aisle URIRepresentation]];
    [dictionaryRepresentation setValue:aisleURIs forKey:@"aisles"];
    return dictionaryRepresentation;
}

-(void)moveToContainer:(NSManagedObject *)container {
    if ([container isKindOfClass:[RNCategory class]]) {
        [self setCategory:(RNCategory *)container];
        [[self listItems] makeObjectsPerformSelector:@selector(setCategory:) withObject:container];
        return;
    }
    if ([container isKindOfClass:[RNAisle class]]) {
        NSSet *aislesInTheSameStore = [[self aisles] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"store == %@", [(RNAisle *)container store]]];
        if ([aislesInTheSameStore count] > 0) {
            [self removeAisles:aislesInTheSameStore];
            [[self listItems] makeObjectsPerformSelector:@selector(removeAisles:) withObject:aislesInTheSameStore];
        }
        
        [self addAislesObject:(RNAisle *)container];
        [[self listItems] makeObjectsPerformSelector:@selector(addAislesObject:) withObject:container];
    }
    if ([container isKindOfClass:[RNFavorites class]]) {
        [self setFavorite:[NSNumber numberWithBool:YES]];
    }
}

-(NSArray *)children {
    return nil;
}

-(NSUInteger)displayIndex {
    return 0;
}

-(NSDate *)dateLastUsed {
    NSSortDescriptor *loggedDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"loggedDate" ascending:YES];
    NSArray *sortedHistoryItems = [[self historyItems] sortedArrayUsingDescriptors:[NSArray arrayWithObject:loggedDateDescriptor]];
    return [[sortedHistoryItems lastObject] valueForKey:@"loggedDate"];
}

@end
